import { InfoCircleOutlined } from '@ant-design/icons'
import { Button, Card, Flex, Popconfirm, Table, Tooltip } from 'antd'
import { useState } from 'react'

export default function DataTable({
  cardTitle = '',
  cardExtra = [],
  pagination = {},
  children,
  ...tableProps
}) {
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const rowSelection = {
    checkStrictly: true, // 父子节点选中状态不再关联
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRowKeys(selectedRowKeys)
    },
    onSelect: (record, selected, selectedRows) => {
      console.log(record, selected, selectedRows)
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      console.log(selected, selectedRows, changeRows)
    },
  }

  return (
    <div className="p-2!">
      <Card
        title={cardTitle}
        extra={
          <Flex gap="small" wrap>
            {cardExtra &&
              cardExtra.map((extra) => {
                const { key, tooltip, confirm, onConfirm, ...extraProps } = extra
                const children = confirm ? (
                  <ConfirmBtn
                    key={key}
                    {...extraProps}
                    onConfirm={() => onConfirm(selectedRowKeys)}
                  />
                ) : (
                  <Button key={key} variant="solid" {...extraProps} />
                )
                return tooltip ? (
                  <TooltipBtn key={key} tooltip={tooltip} children={children} />
                ) : (
                  children
                )
              })}
          </Flex>
        }>
        <Table
          bordered
          rowKey={(record) => record.id}
          rowSelection={rowSelection}
          {...tableProps}
          pagination={
            pagination && { position: ['bottomCenter'], showQuickJumper: true, ...pagination }
          }
        />
        {children}
      </Card>
    </div>
  )
}
export function TooltipBtn({ tooltip, children }) {
  return (
    <Tooltip title={tooltip} key={tooltip}>
      {children}
    </Tooltip>
  )
}

export function ConfirmBtn({ onConfirm, ...extra }) {
  return (
    <Popconfirm
      title="确认删除所选数据？"
      description="此操作不可恢复，请谨慎操作！"
      icon={<InfoCircleOutlined style={{ color: 'red' }} />}
      okText="确认"
      cancelText="取消"
      onConfirm={onConfirm}>
      <Button variant="solid" {...extra} />
    </Popconfirm>
  )
}
